from fastapi import FastAPI,Query
import uvicorn
from sqlalchemy.orm import Session
from sqlalchemy import and_
from service.user_service import router as user_router
app = FastAPI()

app.include_router(user_router)


@app.get("/")
async def root():
    return {"message": "Hello World"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}

from config.mysql_config import get_db
from models.entities import PowerPlant
from pojo.entities import PowerPlantPo
@app.get("/hi")
async def say_hello():
    with get_db() as db:  # 确保会话被正确管理
        powerPlant = PowerPlant(power_plant_date="2024-11-11", month_power_generation=12.21, unit="机组")
        db.add(powerPlant)
        db.commit()
    return {"message": f"添加成功"}

@app.get("/getAll")
async def get_all_power_plants():
    with get_db() as db:
        powerPlants = db.query(PowerPlant).all()  # 查询所有记录
    return [{"id": plant.id,
             "power_plant_date": plant.power_plant_date,
             "month_power_generation": plant.month_power_generation,
             "unit": plant.unit} for plant in powerPlants]

@app.put("/update_power_plant")
async def update_power_plant(powerPlant: PowerPlantPo):
    with get_db() as db:
        db_power_plant = db.query(PowerPlant).filter(PowerPlant.id == powerPlant.id).first()
        if db_power_plant:
            db_power_plant.power_plant_date = powerPlant.power_plant_date
            db_power_plant.month_power_generation = powerPlant.month_power_generation
            db_power_plant.unit = powerPlant.unit

            db.commit()  # 提交事务
            db.refresh(db_power_plant)  # 确保数据已经被提交并刷新到数据库
            print(f"Updated power plant: {db_power_plant}")  # 打印确认是否更新
            return {"message": "更新成功"}

    return {"message": "未找到该电厂信息"}

@app.post("/addpow")
async def add_power_plant(powerPlant: PowerPlantPo):
    with get_db() as db:
        powerPlant = PowerPlant(power_plant_date=powerPlant.power_plant_date,month_power_generation=powerPlant.month_power_generation,unit=powerPlant.unit)
        db.add(powerPlant)  # 将实体添加到会话
        db.commit()  # 提交事务
    return {"message": "添加成功"}

@app.delete("/deletepower/{plant_id}")
async def delete_power_plant(plant_id: int):
    with get_db() as db:
        powerPlant = db.query(PowerPlant).filter(PowerPlant.id == plant_id).first()
        if powerPlant:
            db.delete(powerPlant)  # 删除数据
            db.commit()  # 提交事务
            return {"message": "删除成功"}
    return {"message": "未找到该电厂信息"}

@app.get("/powerplants")
async def get_power_plants(
        page: int = 1,  # 默认第一页
        size: int = 10,  # 默认每页10条
        name: str = Query(None),  # 过滤条件：电厂名称
        location: str = Query(None)  # 过滤条件：电厂位置
):
    offset = (page - 1) * size  # 计算偏移量

    with get_db() as db:
        # 构造查询过滤条件
        query_filters = []
        if name:
            query_filters.append(PowerPlant.unit.like(f"%{name}%"))
        if location:
            query_filters.append(PowerPlant.power_plant_date.like(f"%{location}%"))

        # 使用and_将多个过滤条件组合
        query = db.query(PowerPlant).filter(and_(*query_filters)) if query_filters else db.query(PowerPlant)

        # 获取总数
        total_count = query.count()

        # 获取分页后的数据
        power_plants = query.offset(offset).limit(size).all()

        # 计算总页数
        total_pages = (total_count + size - 1) // size

        return {
            "total_count": total_count,
            "total_pages": total_pages,
            "page": page,
            "size": size,
            "power_plants": power_plants
        }


if __name__ == '__main__':
    uvicorn.run(app,port=5010)